package com.weasing.res.web.action.base;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;
import com.weasing.res.utils.PageBean;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * 
 * @author 黄龙
 *
 */
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
	public static final String HOME = "home";
	public static final String UNAUTHORIZED = "unauthorized";
	
	//用受保护的   子类就可以反问道
	protected T model;
	public T getModel() {
		return model;
	}
	//分页的属性
	protected PageBean pageBean = new PageBean();
	// public int currentPage; // 赋值的时候调用set方法 直接给值给 pageBean
//	protected int rows; 所以可以不用赋值page

	
	protected DetachedCriteria detachedCriteria =null;
	
	//用构造器或者调用这的class
	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public BaseAction() {
		ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
		Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
		Class<T> entityClass = (Class<T>) actualTypeArguments[0];
		//分页离线查询   需要的参数是表的类型
		detachedCriteria =  DetachedCriteria.forClass(entityClass);
		pageBean.setDetachedCriteria(detachedCriteria);
		try {
			model = entityClass.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 将指定java转成json 除去不需要的数据
	 * 并且响应到客户端  
	 * @param exclueds
	 */
	public void java2Json(Object o,String[] exclueds){
		JsonConfig jsonConfig = new JsonConfig();
		//指定那些属性不需要装json
		jsonConfig.setExcludes(exclueds);
		// JSONObject----将单一的对象转化为json
		// JSONArray--将一个集合或者数组对象变为json
		String json = JSONObject.fromObject(o).toString();
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		
		try {
			ServletActionContext.getResponse().getWriter().print(json);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 获取值栈
	protected ValueStack getValueStack() {
		return ActionContext.getContext().getValueStack();
	}
}
